package srvbiz

import (
	"cloud_worm/access/server/client"
	"cloud_worm/util/proto/ujson"
	"github.com/golang/glog"
	"cloud_worm/util/uconst"
	"fmt"
	"cloud_worm/util/proto/uweapon"
	"cloud_worm/access/server/rpcclient"
)

type MsgWeaponResp struct {
}

func (w *MsgWeaponResp) Deal(agent *client.Agent, data []byte) {
	var msg ujson.MsgWpResp
	if err := msg.UnmarshalJSON(data); err != nil {
		glog.Errorf("weapon resp msg Unmarshal error: %s", err.Error())
		return
	}

	err := w.handleBiz(agent, &msg)
	if err != nil {
		glog.Errorf("handle'%s' weapon response msg err: %s", agent.IP, err.Error())
		return
	}

	postData := &rpcclient.WeaponEvent{
		AgentId: agent.Id,
		AgentIP: agent.IP,
		TaskId: msg.TaskId,
		WeaponId: msg.WpId,
		NeedAgain: true,
	}
	rpcclient.PushClient.PushOneC <- postData

	return
}

func (w *MsgWeaponResp) handleBiz(agent *client.Agent, msg *ujson.MsgWpResp) error {
	if len(msg.Id) != uconst.AgentIdLen || len(msg.TaskId) <= 0 || msg.WpId == 0 {
		return fmt.Errorf("weapon response msg content something wrong")
	}

	var wpResult uweapon.WeaponResult
	if err := wpResult.UnmarshalJSON([]byte(msg.Output)); err != nil {
		// 外部解析失败的，则直接更新到weapon log记录中
		// TODO: 解析错误，将错误信息记录下来
	} else {
		// 外部解析成功，则分析写入到weapon log和weapon alert log中
		// TODO: 将alert信息记录下来

		// TODO: 将log信息记录下来
	}

	return nil
}